package com.wzcl.app.service.impl;

import com.wzcl.app.dao.model.Commodity;
import com.wzcl.app.dao.model.Specifications;
import com.wzcl.app.dao.repository.SpecificationsRepository;
import com.wzcl.app.model.common.BusinessException;
import com.wzcl.app.model.common.CodeMsg;
import com.wzcl.app.model.dto.SpecificationsDto;
import com.wzcl.app.service.CommodityService;
import com.wzcl.app.service.SpecificationsService;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.List;
import java.util.stream.Collectors;

@Log4j2
@Service
@Transactional
public class SpecificationsServiceImpl implements SpecificationsService {

    @Autowired
    private SpecificationsRepository repository;


    @Autowired
    private CommodityService commodityService;

    @Override
    public List<Specifications> addAll(List<SpecificationsDto> list) {
        Integer commodityId = list.get(0).getCommodityId();
        Commodity commodity = commodityService.getAndCheckById(commodityId);
        if(!commodity.getSpec()){
            throw new BusinessException(CodeMsg.SYSTEM_ERR,"当前活动没有开启规格配置");
        }
        //删除原有的
        repository.deleteAllByCommodityId(commodityId);
        //添加新增的
        List<Specifications> collect = list.stream().map(specificationsDto -> {
                    Specifications specifications = new Specifications();
                    BeanUtils.copyProperties(specificationsDto, specifications);
                    specifications.setPrice(new BigDecimal(specificationsDto.getPrice()));
                    return specifications;
                }
        ).collect(Collectors.toList());
        return repository.saveAll(collect);
    }

    @Override
    public List<Specifications> getAllByCommodityId(Integer commodityId) {
        return repository.findAllByCommodityId(commodityId);
    }

    @Override
    public Specifications getByCommodityIdAndSpec(Integer commodityId, String spec) {
        if(commodityId == null || StringUtils.isBlank(spec)){
            throw new BusinessException(CodeMsg.MUST_BE_NOT_NULL,"缺少产品及其规格");
        }
        return repository.findByCommodityIdAndSpec(commodityId,spec);
    }

    @Override
    public void deleteByCommodityId(Integer commodityId) {
        repository.deleteAllByCommodityId(commodityId);
    }

    @Override
    public Specifications getAndCheckById(Integer id) {
        if(id == null){
            throw new BusinessException(CodeMsg.MUST_BE_NOT_NULL,"缺少规格Id");
        }
        Specifications specifications = repository.findById(id).orElse(null);
        if(specifications == null){
            throw new BusinessException(CodeMsg.SPEC_NOT_EXIST);
        }
        return specifications;
    }
}
